package com.xiehua.task.job.bucket;

import com.xiehua.task.actor.cmd.NotifyClient;
import com.xiehua.task.job.RidesOperationDefualt;
import com.xiehua.task.msg.FixedTaskMetaData;
import org.tio.core.GroupContext;
import org.tio.core.Node;
import org.tio.server.ServerGroupContext;
import redis.clients.jedis.Jedis;

import java.util.List;

public class CronBucket extends RidesOperationDefualt {

    public static final String KEY_CRON_INFO_PIX = "cron_info_";//cron_info_b2c(com.xx.xx,0 15 10 ? * *)

    public CronBucket(Jedis jedis) {
        super(jedis);
    }

    /**
     * 添加 cron 表达式
     * **/
    public void addCron(String topicName,String className,String methodName,String cron){
        String key = KEY_CRON_INFO_PIX + topicName;
        String field = className + "." + methodName;
        if(jedis.hexists(key,field)) return ;
        jedis.hset(key,field,cron);
    }

    /***
     * 客户端下线时，移除所有节点都下线的topic对应的cron表达式
     * **/
    public void delCron(Node node, GroupContext context){
        List<String> list = new TopicBucket(jedis).queryTopic(node);
        TopicBucket topicBucket = new TopicBucket(jedis);
        list.forEach(s ->{
            List<NotifyClient> clients = topicBucket.querySurvivalChannelByTopicName(s,context);
            if( clients == null || clients.size() < 1){//没有存活的节点
                jedis.del(KEY_CRON_INFO_PIX + s);
            };
        });
    }

    /***
     * 客户端连接成功后更新cron
     * **/
    public void updateTopicCron(String topicName, List<FixedTaskMetaData> list){
        String key = KEY_CRON_INFO_PIX + topicName;
        //delete cron
        jedis.del(key);
       //insert
        list.forEach(s ->{
            String field = s.getClassName() + "." + s.getMethodName();
            jedis.hset(key,field,s.getCron());
        });
    }


}
